/**
 * 
 */
package com.qolome.filter;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import com.qolome.exception.RateLimitException;

/**
 * @Description: 限流
 * @author 姜锋
 * @date 2020年1月24日 下午7:27:49 
 * @version V1.0   
 *
 */
public class RateLimitFiler extends ZuulFilter{

	private final RateLimiter RATELIMITER = RateLimiter.create(100);
	
	/* （非 Javadoc）
	 * @see com.netflix.zuul.IZuulFilter#shouldFilter()
	 */
	@Override
	public boolean shouldFilter() {
		return false;
	}

	/* （非 Javadoc）
	 * @see com.netflix.zuul.IZuulFilter#run()
	 */
	@Override
	public Object run() throws ZuulException {
		if(!RATELIMITER.tryAcquire()) {
			throw new RateLimitException();
		}
		
		return null;
	}

	/* （非 Javadoc）
	 * @see com.netflix.zuul.ZuulFilter#filterType()
	 */
	@Override
	public String filterType() {
		return POST_TYPE;
	}

	/* （非 Javadoc）
	 * @see com.netflix.zuul.ZuulFilter#filterOrder()
	 */
	@Override
	public int filterOrder() {
		return SERVLET_DETECTION_FILTER_ORDER-1;
	}
}
